# -*- coding:utf-8 -*-
import datetime
import logging
import traceback
from django.conf import settings
from django.http import JsonResponse
from django.contrib import auth
from django.utils.deprecation import MiddlewareMixin
from .my_auth import get_user_by_token


elapse_logger = logging.getLogger('elapse_log')
except_logger = logging.getLogger('except_log')
debug_log_logger = logging.getLogger('debug_log')


class BaziElapseMiddleware(MiddlewareMixin):
    def process_request(self, request):
        self.start = datetime.datetime.now()

    def process_response(self, request, response):
        get_para = ['%s:%s' % (k, v) for k, v in request.GET.items()]
        # 密码不要记录
        post_para = ['%s:%s' % (k, v) for k, v in request.POST.items()]
        access_line = ['elapse: %s' % str(datetime.datetime.now() - self.start),
                       'method: %s' % request.method,
                       'ip: %s' % request.META['REMOTE_ADDR'],
                       'status: %s' % response.status_code,
                       'path: %s' % request.path,
                       'GET: %s' % str(get_para),
                       'POST: %s' % str(post_para),
                       'User-Agent: %s' % request.META.get('HTTP_USER_AGENT', '')]
        elapse_logger.info(', '.join(access_line))
        return response


class BaziExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        """
        process_exception() 应当返回 None 或 HttpResponse 对象
        """
        except_logger.error(traceback.format_exc())

    def process_response(self, request, response):
        if settings.DEBUG:
            return response
        if response.status_code == 500:
            return JsonResponse({'code': 500, 'msg': u'服务器异常,请联系管理员:('}, status=500)
        elif response.status_code == 404:
            return JsonResponse({'code': 404, 'msg': u'找不到对象:('}, status=404)
        return response


class MyAuthBackend:
    def authenticate(self, user_id=None):
        return self.get_user(user_id)

    def get_user(self, user_id):
        try:
            UserModel = auth.get_user_model()
            return UserModel.objects.get(id=user_id)
        except:
            return None


class MyAuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        auth_field = request.META.get('HTTP_AUTHORIZATION', '')
        if auth_field:
            symbol, token = auth_field.split()
            assert symbol == 'bazi'
            user = get_user_by_token(token)
            if user:
                request.user = user
